package com.easyselection.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easyselection.dto.LoginFormDTO;
import com.easyselection.dto.Result;
import com.easyselection.dto.UserDTO;
import com.easyselection.entity.User;
import com.easyselection.mapper.UserMapper;
import com.easyselection.service.IUserService;
import com.easyselection.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //2.不符合, 返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //3.符合,生成验证码
        String code = RandomUtil.randomNumbers(6);

        //4.保存验证码到redis中, 并设置有效期2分钟
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone,
                code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

//        //4.保存验证码信息到session
//        session.setAttribute("code", code);

        //5.发送验证码 (模拟实现)
        log.debug("发送验证码成功, 验证码:{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            //2.不符合, 返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //2.校验验证码
        //从redis当中获取
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);

        if(cacheCode == null || !loginForm.getCode().equals(cacheCode)){
            //3.不一致,报错
            return Result.fail("验证码错误！");
        }

        //4.一致, 根据手机号查询用户
        User user = query().eq("phone", phone).one();

        //5.查询用户是否存在
        if(user == null){
            //6.不存在, 创建新用户保存到数据库
            user = createUserWithPhone(phone);
        }

        //7.存在, 保存到redis中

//        //7.1 随机生成token, 作为登录令牌，存储到redis当中
//        String token = UUID.randomUUID().toString(true);

//        //7.2 将User对象转换为hashMap存储
//        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//        //Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
//        //因为stringRedisTemplate的KV结构都为string类型, 需要将userDTO中的id的Long类型转换为String类型,否则会抛出类型转换异常
//        //方法一:自己单独将非字符串属性转换为字符串
////        Long id = (Long) userMap.get("id");
////        userMap.put("id", id.toString());
//        //方法二: 通过api参数指定
//        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
//                        CopyOptions.create()
//                        .setIgnoreNullValue(true)
//                        .setFieldValueEditor((fieldKey, filedValue)-> filedValue.toString()
//                )
//        );
//        //7.3 存储 并设置有效期
//        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
//        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
//        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);

        //7.1使用jwt令牌技术做登录鉴权
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("nickName", user.getNickName());
        map.put("icon", user.getIcon());

        //7.2 将User对象转换为hashMap存储
       UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldKey, filedValue)-> filedValue.toString())
        );

        String token = JwtUtils.generateJWT(map);
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;

        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        //设置有效期
        stringRedisTemplate.expire(tokenKey,RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);

        //返回token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2.获取当前日期
        LocalDateTime now = LocalDateTime.now();
        String suffix = now.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        //3.拼接key
        String key = RedisConstants.USER_SIGN_KEY + userId + suffix;
        //4.获取当前天数是这一个月的第几天
        int dayOfMonth = now.getDayOfMonth();

        //5.写入redis setbit key offset value
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1 , true);
        return Result.ok();
    }

    @Override
    public Result countSign() {
        Long userId = UserHolder.getUser().getId();
        //1. 获取当前日期
        LocalDateTime now = LocalDateTime.now();
        String suffix = now.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        //2. 获取当天天是这个月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //3. 拼接key
        String key = RedisConstants.USER_SIGN_KEY + userId + suffix;
        //4. 获取本月截止今天为止所有的签到记录  BITFIELD sign:5:2025/05 get u26 0
        //返回值: 11100000000000000000000001000000
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (result == null || result.isEmpty()) {
            return Result.ok(0);
        }
        Long num = result.get(0);
        int count = 0;//统计连续签到天数
        if(num == null || num == 0) return Result.ok(0);
        while(true){
            if((num & 1) == 1) count++;//说明用户今天已签到
            else break;//说明用户今天未签到
            num >>= 1;
        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        //1. 创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        //新用户保存到数据库
        save(user);
        return user;
    }
}
